package com.peng.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.peng.dao.UserMapper;
import com.peng.entity.Role;
import com.peng.dao.RoleMapper;
import com.peng.entity.User;
import com.peng.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.peng.vo.query.RoleQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
@Transactional
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {


    @Resource
    private UserMapper userMapper;

    /**
     * 查询角色列表
     *
     * @param page
     * @param roleQueryVo
     * @return
     */
    @Override
    public IPage<Role> findRoleListByUserId(IPage<Role> page, RoleQueryVo roleQueryVo) {
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        //条件查询
        queryWrapper.like(!ObjectUtils.isEmpty(roleQueryVo.getRoleName()), Role::getRoleName, roleQueryVo.getRoleName());
        // 根据id升序
        queryWrapper.orderByAsc(Role::getId);
        // 根据用户id查询用户信息
        User user = userMapper.selectById(roleQueryVo.getUserId());
        // 判断对象是否为空
        if (user != null && !ObjectUtils.isEmpty(user.getIsAdmin()) && user.getIsAdmin() != 1) {
            // 非管理员只能查询子集创建的角色
            queryWrapper.eq(Role::getCreateUser, roleQueryVo.getUserId());
        }
        return baseMapper.selectPage(page, queryWrapper);
    }

    /**
     * 检测角色是否被使用
     *
     * @param id
     * @return
     */
    @Override
    public boolean hasRoleCount(Long id) {

        return baseMapper.getRoleCountByRoleId(id) > 0;
    }

    /**
     * 删除用户角色
     *
     * @param id
     * @return
     */
    @Override
    public boolean deleteRoleById(Long id) {
        // 删除角色权限关系
        baseMapper.deleteRolePermissionByRoleId(id);
        return baseMapper.deleteById(id) > 0;
    }

    /**
     * 保存角色权限关系
     *
     * @param roleId
     * @param permissionIds
     * @return
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean saveRolePermission(Long roleId, List<Long> permissionIds) {

        // 删除角色权限信息
        baseMapper.deleteRolePermissionByRoleId(roleId);
        // 保存角色权限关系
        return baseMapper.saveRolePermission(roleId, permissionIds) > 0;
    }

    /**
     * 根据用户id查询该用户所拥有的角色id
     *
     * @param userId
     * @return
     */
    @Override
    public List<Long> findRoleIdByUserId(Long userId) {
        return baseMapper.findRoleIdByUserId(userId);
    }
}
